package net.lab1024.sa.admin.module.business.purchase.supplier.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.lab1024.sa.admin.module.business.purchase.supplier.dao.SupplierDao;
import net.lab1024.sa.admin.module.business.purchase.supplier.domain.entity.SupplierEntity;
import net.lab1024.sa.admin.module.business.purchase.supplier.domain.form.SupplierAddForm;
import net.lab1024.sa.admin.module.business.purchase.supplier.domain.form.SupplierQueryForm;
import net.lab1024.sa.admin.module.business.purchase.supplier.domain.form.SupplierUpdateForm;
import net.lab1024.sa.admin.module.business.purchase.supplier.domain.vo.SupplierVO;
import net.lab1024.sa.base.common.code.UserErrorCode;
import net.lab1024.sa.base.common.domain.PageResult;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.util.SmartBeanUtil;
import net.lab1024.sa.base.common.util.SmartPageUtil;
import net.lab1024.sa.base.module.support.operatelog.annotation.OperateLog;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 供应商服务
 *
 * @Author 1024创新实验室
 * @Date 2024/07/19 20:30:00
 * @Wechat zhuoda1024
 * @Email lab1024@163.com
 * @Copyright <a href="https://1024lab.net">1024创新实验室</a>
 */
@Service
public class SupplierService {

    @Resource
    private SupplierDao supplierDao;

    /**
     * 分页查询供应商
     */
    public ResponseDTO<PageResult<SupplierVO>> queryPage(SupplierQueryForm queryForm) {
        Page<?> page = SmartPageUtil.convert2PageQuery(queryForm);
        List<SupplierVO> list = supplierDao.queryPage((Page<SupplierVO>) page, queryForm);
        PageResult<SupplierVO> pageResult = SmartPageUtil.convert2PageResult(page, list);
        return ResponseDTO.ok(pageResult);
    }

    /**
     * 添加供应商
     */
    @Transactional(rollbackFor = Exception.class)
    @OperateLog
    public ResponseDTO<String> add(SupplierAddForm addForm, Long userId, String userName) {
        // 校验供应商编码是否重复
        SupplierEntity existCode = supplierDao.selectByCode(addForm.getSupplierCode(), false);
        if (existCode != null) {
            return ResponseDTO.userErrorParam("供应商编码已存在");
        }

        // 校验供应商名称是否重复
        SupplierEntity existName = supplierDao.selectByName(addForm.getSupplierName(), false);
        if (existName != null) {
            return ResponseDTO.userErrorParam("供应商名称已存在");
        }

        // 转换并保存
        SupplierEntity supplierEntity = SmartBeanUtil.copy(addForm, SupplierEntity.class);
        supplierEntity.setCreateUserId(userId);
        supplierEntity.setCreateUserName(userName);
        supplierEntity.setCreateTime(LocalDateTime.now());
        supplierEntity.setUpdateUserId(userId);
        supplierEntity.setUpdateUserName(userName);
        supplierEntity.setUpdateTime(LocalDateTime.now());
        supplierEntity.setDeletedFlag(false);

        // 设置默认信用等级
        if (StringUtils.isBlank(supplierEntity.getCreditRating())) {
            supplierEntity.setCreditRating("C");
        }

        supplierDao.insert(supplierEntity);
        return ResponseDTO.ok();
    }

    /**
     * 更新供应商
     */
    @Transactional(rollbackFor = Exception.class)
    @OperateLog
    public ResponseDTO<String> update(SupplierUpdateForm updateForm, Long userId, String userName) {
        // 校验供应商是否存在
        SupplierEntity existEntity = supplierDao.selectById(updateForm.getSupplierId());
        if (existEntity == null || existEntity.getDeletedFlag()) {
            return ResponseDTO.error(UserErrorCode.DATA_NOT_EXIST);
        }

        // 校验供应商编码是否重复（排除自己）
        SupplierEntity existCode = supplierDao.selectByCode(updateForm.getSupplierCode(), false);
        if (existCode != null && !existCode.getSupplierId().equals(updateForm.getSupplierId())) {
            return ResponseDTO.userErrorParam("供应商编码已存在");
        }

        // 校验供应商名称是否重复（排除自己）
        SupplierEntity existName = supplierDao.selectByName(updateForm.getSupplierName(), false);
        if (existName != null && !existName.getSupplierId().equals(updateForm.getSupplierId())) {
            return ResponseDTO.userErrorParam("供应商名称已存在");
        }

        // 转换并更新
        SupplierEntity supplierEntity = SmartBeanUtil.copy(updateForm, SupplierEntity.class);
        supplierEntity.setUpdateUserId(userId);
        supplierEntity.setUpdateUserName(userName);
        supplierEntity.setUpdateTime(LocalDateTime.now());

        // 设置默认信用等级
        if (StringUtils.isBlank(supplierEntity.getCreditRating())) {
            supplierEntity.setCreditRating("C");
        }

        supplierDao.updateById(supplierEntity);
        return ResponseDTO.ok();
    }

    /**
     * 删除供应商
     */
    @Transactional(rollbackFor = Exception.class)
    @OperateLog
    public ResponseDTO<String> delete(Long supplierId, Long userId, String userName) {
        // 校验供应商是否存在
        SupplierEntity existEntity = supplierDao.selectById(supplierId);
        if (existEntity == null || existEntity.getDeletedFlag()) {
            return ResponseDTO.error(UserErrorCode.DATA_NOT_EXIST);
        }

        // TODO: 校验是否有关联的采购记录，如果有则不能删除

        // 软删除
        SupplierEntity supplierEntity = new SupplierEntity();
        supplierEntity.setSupplierId(supplierId);
        supplierEntity.setDeletedFlag(true);
        supplierEntity.setUpdateUserId(userId);
        supplierEntity.setUpdateUserName(userName);
        supplierEntity.setUpdateTime(LocalDateTime.now());

        supplierDao.updateById(supplierEntity);
        return ResponseDTO.ok();
    }

    /**
     * 查询供应商详情
     */
    public ResponseDTO<SupplierVO> queryDetail(Long supplierId) {
        SupplierEntity supplierEntity = supplierDao.selectById(supplierId);
        if (supplierEntity == null || supplierEntity.getDeletedFlag()) {
            return ResponseDTO.error(UserErrorCode.DATA_NOT_EXIST);
        }

        SupplierVO supplierVO = SmartBeanUtil.copy(supplierEntity, SupplierVO.class);
        
        // 设置描述字段
        if (supplierEntity.getSupplierType() != null) {
            switch (supplierEntity.getSupplierType()) {
                case 1:
                    supplierVO.setSupplierTypeDesc("个人");
                    break;
                case 2:
                    supplierVO.setSupplierTypeDesc("企业");
                    break;
                default:
                    supplierVO.setSupplierTypeDesc("未知");
                    break;
            }
        }

        if (StringUtils.isNotBlank(supplierEntity.getCreditRating())) {
            switch (supplierEntity.getCreditRating()) {
                case "A":
                    supplierVO.setCreditRatingDesc("优秀");
                    break;
                case "B":
                    supplierVO.setCreditRatingDesc("良好");
                    break;
                case "C":
                    supplierVO.setCreditRatingDesc("一般");
                    break;
                case "D":
                    supplierVO.setCreditRatingDesc("差");
                    break;
                default:
                    supplierVO.setCreditRatingDesc("未知");
                    break;
            }
        }

        if (supplierEntity.getStatus() != null) {
            switch (supplierEntity.getStatus()) {
                case 0:
                    supplierVO.setStatusDesc("禁用");
                    break;
                case 1:
                    supplierVO.setStatusDesc("启用");
                    break;
                default:
                    supplierVO.setStatusDesc("未知");
                    break;
            }
        }

        return ResponseDTO.ok(supplierVO);
    }

    /**
     * 启用/禁用供应商
     */
    @Transactional(rollbackFor = Exception.class)
    @OperateLog
    public ResponseDTO<String> updateStatus(Long supplierId, Integer status, Long userId, String userName) {
        // 校验供应商是否存在
        SupplierEntity existEntity = supplierDao.selectById(supplierId);
        if (existEntity == null || existEntity.getDeletedFlag()) {
            return ResponseDTO.error(UserErrorCode.DATA_NOT_EXIST);
        }

        // 更新状态
        SupplierEntity supplierEntity = new SupplierEntity();
        supplierEntity.setSupplierId(supplierId);
        supplierEntity.setStatus(status);
        supplierEntity.setUpdateUserId(userId);
        supplierEntity.setUpdateUserName(userName);
        supplierEntity.setUpdateTime(LocalDateTime.now());

        supplierDao.updateById(supplierEntity);
        return ResponseDTO.ok();
    }

    /**
     * 获取所有启用的供应商列表
     */
    public ResponseDTO<List<SupplierEntity>> queryEnabledList() {
        List<SupplierEntity> list = supplierDao.selectByStatus(1, false);
        return ResponseDTO.ok(list);
    }
}